package algorithm.leetCode.other;

class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
	}
}

public class ListNode1 {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		if (length(l2) > length(l1)) {
			ListNode tmp = l1;
			l1 = l2;
			l2 = tmp;
		}
		ListNode head = l1;
		while (l2.next != null) {
			l1.val += l2.val;
			l1 = l1.next;
			l2 = l2.next;
		}
		l1.val += l2.val;
		l1 = head;
		while (l1.next != null) {
			if (l1.val >= 10) {
				l1.next.val += 1;
				l1.val -= 10;
			}
			l1 = l1.next;
		}
		if (l1.val >= 10) {
			l1.val -= 10;
			ListNode newNode = new ListNode(1);
			newNode.next = null;
			l1.next = newNode;
		}
		return head;
	}

	public int length(ListNode node) {
		int x = 1;
		while (node.next != null) {
			node = node.next;
			x++;
		}
		return x;
	}
}
